import http from "@/utils/request.js"

const getWxCode = () => {
	return new Promise((resolve, reject) => {
		wx.login({
			success: (wxRes) => {
				resolve(wxRes.code)
			}
		})
	})
}

const getAccessData = (code) => {
	return new Promise((resolve, reject) => {
		http.post('login/mnpLogin', {
			code
		}).then(res => {
			resolve(res.result);
		})
	})
}

export default {
	state: {
		token: uni.getStorageSync("user_token"),
		userInfo: uni.getStorageSync("userInfo"),
		messageStats: null
	},
	mutations: {
		login(state, userInfo) {
			state.token = userInfo.token;
			state.userInfo = userInfo.user;

			uni.setStorageSync("userInfo", userInfo.user);
			uni.setStorageSync("user_token", userInfo.token);
		},
		set_info(state, userInfo) {
			state.userInfo = userInfo;
			uni.setStorageSync("userInfo", userInfo);
		},
		logout(state) {
			state.token = null;
			state.userInfo = null;
			uni.removeStorageSync("user_token");
			uni.removeStorageSync("userInfo");
		},
		set_message(state, data) {
			state.messageStats = data
		}
	},
	actions: {
		async mnpLogin(context, params) {
			const wxCode = await getWxCode()
			const userInfo = await getAccessData(wxCode)
			context.commit('login', userInfo)
		},
		getMessage(context) {
			http.post('message/getMessageStats').then(res => {
				context.commit('set_message', res.result)
			});
		}
	}
}